<template>
  <view class="page-container">
    <!-- 标题栏 -->
    <view class="header">
      <text class="progress-text" style="color: purple; text-align: center; width: 100%;">
        已完成{{ currentStep}}/3
      </text>
    </view>
    <!-- 进度条 -->
    <view class="progress-bar">
      <view class="progress" :style="{ width: progressWidth, backgroundColor: progressColor }"></view>
    </view>
    <!-- 舌部细节采集标题 -->
    <view class="title-container">
      <text class="title">舌部细节采集</text>
    </view>
    
    <!-- 主要内容区域 -->
    <view class="main-content" :style="{ backgroundColor: mainContentBgColor }">
      <!-- 初始显示区域 (步骤1) -->
      <view v-show="!showCamera && !showPhotoResult && currentStep === 0 && !showSummary">
        <view class="image-container">
          <image src="@/static/example1.png" mode="aspectFit"></image>
        </view>
        <view class="tip-container">
          <text class="tips">请将舌头置于虚线框内，确保光线充足</text>
        </view>
        <view class="button-container">
          <button @click="startProcess(1)" class="open-camera-btn">开始拍摄</button>
        </view>
      </view>
      
      <!-- 步骤2的样例展示区域 -->
      <view v-show="!showCamera && !showPhotoResult && currentStep === 1 && !showSummary">
        <view class="image-container">
          <image src="@/static/example2.png" mode="aspectFit"></image>
        </view>
        <view class="tip-container">
          <text class="tips">请将舌头置于虚线框内，确保光线充足</text>
        </view>
        <view class="button-container">
          <button @click="startProcess(2)" class="open-camera-btn">开始拍摄</button>
        </view>
      </view>
      
      <!-- 步骤3的样例展示区域 -->
      <view v-show="!showCamera && !showPhotoResult && currentStep === 2 && !showSummary">
        <view class="image-container">
          <image src="@/static/example3.png" mode="aspectFit"></image>
        </view>
        <view class="tip-container">
          <text class="tips">请将人脸置于虚线框内，确保光线充足</text>
        </view>
        <view class="button-container">
          <button @click="startProcess(3)" class="open-camera-btn">开始拍摄</button>
        </view>
      </view>
      
      <!-- 摄像头区域 -->
      <view class="camera-container" v-if="showCamera && !showPhotoResult && !showSummary">
		  <os :osName="osName">
			  <template #[osName]>
			  	  <camera 
			  	          :device-position="cameraPosition" 
			  	          style="width: 100%; height: 60vh"
			  	          flash="off"
					></camera>
			  </template>
		  </os>

        <!-- 椭圆框叠加层 -->
        <view class="overlay" :style="{ alignItems: overlayAlign }">
          <view 
            class="ellipse-frame" 
            :style="{ 
              width: ellipseWidth, 
              height: ellipseHeight,
              top: ellipseTop
            }"
          >
            <view class="vertical-text">{{ currentPrompt }}</view>
          </view>
        </view>
      </view>
      
      <!-- 拍摄控制按钮 -->
      <view class="camera-control" v-if="showCamera && !showPhotoResult && !showSummary">
        <button @click="takePhoto" class="take-photo-btn">确认拍摄</button>
      </view>
      
      <!-- 显示拍摄结果 -->
      <view v-if="showPhotoResult && !showSummary" class="photo-result-container">
        <image :src="imagePaths[currentStep]" mode="aspectFit"></image>
        <view class="button-group">
          <button @click="restartCurrentStep" class="re-take-btn">重拍</button>
          <button @click="nextStep" class="next-btn">
            {{ currentStep < 2 ? '下一步' : '完成' }}
          </button>
        </view>
      </view>
      
      <!-- 照片汇总视图 -->
      <view v-if="showSummary" class="summary-view">
        <view class="summary-title">拍摄完成</view>
        <view class="photos-grid">
          <view class="photo-item" v-for="(photo, index) in imagePaths" :key="index">
            <image :src="photo" mode="aspectFill"></image>
            <text class="photo-label">{{ ['舌面照', '舌下照', '面部照'][index] }}</text>
          </view>
        </view>
        <view class="summary-buttons">
          <button @click="retakeAllPhotos" class="re-take-all-btn">全部重拍</button>
          <button @click="submitAllPhotos" class="submit-btn">提交诊断</button>
        </view>
      </view>
    </view>
    
    <!-- 拍摄须知 -->
    <view class="tips-container" v-if="!showSummary">
      <view class="tips-title">拍摄须知</view>
      <view class="tips-list">
        <view class="tip-item">一、拍摄前准备</view>
        <view class="tip-bottom">平静状态：拍摄前请保持平静状态，避免进行剧烈运动。若刚运动结束，请静坐3分钟后再进行拍摄。</view>
        <view class="tip-bottom">漱口清洁：拍摄前避免食用或服用易使舌苔染色的饮食（如花生酱、巧克力、茶水）或药物。建议使用清水漱口，以确保舌象清晰。</view>
        <view class="tip-bottom">充足光线：拍摄时请确保环境光线充足，避免在强光直射或昏暗环境下进行拍摄。</view>
        <view class="tip-bottom">手机稳定：拍摄时请保持拍摄手机稳定，避免抖动影响拍摄效果。</view>
        <view class="tip-item">二、拍摄步骤</view>
        <view class="tip-bottom">身体放松：拍摄时请保持身体放松，采取坐位。</view>
        <view class="tip-bottom">张大嘴巴：张大嘴巴，使上唇和下唇尽量分开。</view>
        <view class="tip-bottom">伸出舌头：将舌头自然伸出下嘴唇外，舌尖朝下伸展，贴近下巴，尽量使舌体完全暴露在镜头视野内。</view>
        <view class="tip-bottom">点击采集按钮：将屏幕显示的舌象采集虚线区域对准舌头，确保舌头完全处于采集区域内，按下采集按钮。</view>
        <view class="tip-item">三、拍摄失败处理</view>
        <view class="tip-bottom">休息调整：如果采集不成功，或采集的图片模糊，请将舌头收回，放松嘴巴，休息10秒后再次伸出舌头进行拍照尝试。</view>
        <view class="tip-bottom">多次尝试：若多次尝试仍未成功，请检查拍摄环境光线是否充足、手机是否稳定等因素，必要时可更换拍摄设备或环境后再次尝试。</view>
        <view class="tip-item">感谢您的配合，祝您拍摄顺利！</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShow } from "@dcloudio/uni-app";
import{baseUrl} from '@/utils/request.js';
import os from '../../components/os.vue';

// 状态管理
const showCamera = ref(false)
const showPhotoResult = ref(false)
const showExample = ref(false) 
const showSummary = ref(false) // 新增：汇总视图状态
const imagePaths = ref([]) 
const cameraPosition = ref('front')
const currentStep = ref(0) 
const progressWidth = ref('0%')
const progressColor = ref('#7134A6')
const isUploading = ref(false)

// 椭圆框样式配置（按步骤存储）
const stepConfig = [
  { width: '45%', height: '48%', top: '50%', prompt: '舌象区域' }, 
  { width: '40%', height: '35%', top: '40%', prompt: '舌象区域' }, 
  { width: '60%', height: '65%', top: '30%', prompt: '人脸区域' }, 
]

// 椭圆框样式控制
const overlayAlign = ref('center')
const ellipseWidth = ref('45%')
const ellipseHeight = ref('48%')
const ellipseTop = ref('50%')
const currentPrompt = ref('舌象区域')

// 计算属性
const mainContentBgColor = computed(() => {
  return showCamera.value ? '#fff' : '#EFECFF'
})

const osName = computed(() => uni.getDeviceInfo().osName === 'ios' ? 'ios' : 'anzhuo')

// 生命周期钩子
onMounted(() => {
	console.log(osName);
  checkCameraPermission()
})

// 开始拍摄流程（点击开始拍摄时打开相机）
const startProcess = (value) => {
  showCamera.value = true
  showPhotoResult.value = false
  showExample.value = false
  showSummary.value = false
  cameraPosition.value = 'front'
  
  // 只在第一次调用时初始化数组
  if (imagePaths.value.length === 0) {
    imagePaths.value = [null, null, null]
  }
  
  updateEllipseConfig(value) 
}
// 打开相机（内部使用，根据步骤设置椭圆框）
const openCamera = (step) => {
  showCamera.value = true
  showPhotoResult.value = false
  showSummary.value = false
  cameraPosition.value = 'front'
  updateEllipseConfig(step) 
}

// 更新椭圆框配置
const updateEllipseConfig = (step) => {
  const config = stepConfig[step - 1] || stepConfig[0]
  ellipseWidth.value = config.width
  ellipseHeight.value = config.height
  ellipseTop.value = config.top
  currentPrompt.value = config.prompt
}

// 上传图片函数
const uploadImage = (imagePath, type) => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync("token");
    uni.uploadFile({
      url: `${baseUrl}/photo/upload`,
      filePath: imagePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json' 
      },
      formData: {
        type: type,
      },
      success: (res) => {
        try {
          const { statusCode, data: responseData } = res;
          if (statusCode === 200) {
            resolve(responseData);
          } else {
            reject(new Error(responseData || '上传失败'));
          }
        } catch (e) {
          reject(new Error('解析响应失败'));
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 拍照
const takePhoto = () => {
  const ctx = uni.createCameraContext()
  ctx.takePhoto({
    quality: 'high',
    success: (res) => {
      imagePaths.value[currentStep.value] = res.tempImagePath 
      showCamera.value = false
      showPhotoResult.value = true
    },
    fail: (err) => {
      console.error('拍照失败', err)
      progressColor.value = '#FF4444'
      uni.showToast({ title: '拍照失败，请重试', icon: 'none' })
    }
  })
}

// 重拍当前步骤
const restartCurrentStep = () => {
  const currentIndex = showPhotoResult.value ? currentStep.value : 0 
  imagePaths.value[currentIndex] = null
  openCamera(currentIndex + 1) 
}

// 下一步逻辑
const nextStep = async () => {
  const currentIndex = currentStep.value 
  if (!imagePaths.value[currentIndex]) {
    uni.showToast({ title: '请先拍摄照片', icon: 'none' })
    return
  }
  
  isUploading.value = true
  uni.showLoading({ title: '上传中...' })
  
  try {
    let type;
    if (currentIndex === 0) {
      type = 1; // 舌面
    } else if (currentIndex === 1) {
      type = 2; // 舌下
    } else if (currentIndex === 2) {
      type = 0; // 面相
    }
    
    await uploadImage(imagePaths.value[currentIndex], type);
    
    if (currentStep.value < 2) { 
      currentStep.value++ 
      progressWidth.value = `${((currentStep.value) / 3) * 100}%`
      showExample.value = true
      showCamera.value = false
      showPhotoResult.value = false
      updateEllipseConfig(currentStep.value + 1)
    } else {
      // 所有步骤完成，显示汇总视图
      currentStep.value = 3
      progressWidth.value = '100%'
      showSummary.value = true
      showPhotoResult.value = false
      uni.showToast({ title: '拍摄完成', icon: 'success' })
    }
  } catch (error) {
    console.error('上传失败', error);
    progressColor.value = '#FF4444';
    uni.showToast({ 
      title: error.message || '上传失败，请重试', 
      icon: 'none',
      duration: 3000
    });
  } finally {
    isUploading.value = false
    uni.hideLoading()
  }
}

// 全部重拍
const retakeAllPhotos = () => {
  showSummary.value = false
  currentStep.value = 0
  progressWidth.value = '0%'
  imagePaths.value = []
  openCamera(1)
}

// 提交所有照片
const submitAllPhotos = () => {
  uni.showToast({ title: '照片已提交', icon: 'success' })
  resetProcess()
}

// 重置整个流程
const resetProcess = () => {
  showCamera.value = false
  showPhotoResult.value = false
  showExample.value = false
  showSummary.value = false
  imagePaths.value = []
  currentStep.value = 0
  progressWidth.value = '0%'
}

// 检查相机权限
const checkCameraPermission = async () => {
  try {
    const { authSetting } = await uni.getStorageSync('scope.camera')
    if (!authSetting['scope.camera']) {
      await uni.authorize({ scope: 'scope.camera' })
    }
  } catch (error) {
    if (error?.errMsg?.includes('auth deny')) {
      uni.showModal({
        title: '权限申请',
        content: '需要相机权限才能拍照',
        success: ({ confirm }) => confirm && uni.openSetting()
      })
    }
  }
}
</script>

<style scoped lang="scss">
$purple-color: #7134A6;
$primary-color: #7134A6;
$neutral-color: #ccc;
$text-color: #333;
$background-color: #fff;
$card-bg-color: #EFECFF;
$border-radius: 10px;

.page-container {
  padding: 20px;
  padding-bottom: 0;
  background-color: $background-color;
  
  .header {
    margin-bottom: 10px;
  }
  
  .progress-bar {
    height: 10px;
    background-color: #e0e0e0;
    border-radius: 5px;
    margin-bottom: 20px;
    overflow: hidden;
  }
  
  .progress {
    height: 100%;
    transition: width 0.3s ease;
  }
  
  .progress-text {
    font-size: 30rpx;
    color: $purple-color;
    display: flex;
    justify-content: center;
  }
  
  .title-container {
    text-align: center;
    margin-bottom: 10px;
    
    .title {
      font-size: 35rpx;
      letter-spacing: 1rpx;
      font-weight: bold;
    }
  }
  
  .main-content {
    border-radius: $border-radius;
    margin-bottom: 20px;
    transition: background-color 0.3s ease;
    
    .image-container {
      display: flex;
      justify-content: center;
      margin-bottom: 15px;
      padding-top: 30px;
      
      image {
        width: 80%;
        height: 430rpx;
      }
    }
    
    .tip-container {
      display: flex;
      justify-content: center;
      margin-bottom: 15px;
      font-size: 30rpx;
    }
    
    .button-container {
      padding: 0 20px 25px;
      
      .open-camera-btn {
        border-radius: 8px;
        width: 100%;
        background-color: $primary-color;
        color: white;
      }
    }
    
    .camera-container {
      position: relative;
      width: 100%;
      height: 60vh;
    }
    
    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      pointer-events: none;
      transition: all 0.5s ease;
    }
    
    .ellipse-frame {
      border: 4px dashed white;
      border-radius: 50%;
      box-sizing: border-box;
      position: relative;
      transform: translateY(-50%);
      box-shadow: 0 0 15px rgba(255, 255, 255, 0.5);
      transition: all 0.5s ease;
      
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .vertical-text {
      color: white;
      font-size: 40rpx;
      font-weight: bold;
      text-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
      writing-mode: vertical-lr;
      text-align: center;
      letter-spacing: 5rpx;
    }
    
    .camera-control {
      padding: 15px 20px;
      padding-bottom: 0px;
      display: flex;
      justify-content: center;
      
      .take-photo-btn {
        border-radius: 8px;
        width: 90%;
        background-color: $primary-color;
        color: white;
        font-size: 32rpx;
      }
    }
    
    .photo-result-container {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 20px;
      
      image {
        width: 100%;
        height: 480rpx;
        margin-bottom: 20px;
      }
      
      .button-group {
        display: flex;
        justify-content: space-around;
        width: 100%;
        
        .re-take-btn {
          border-radius: 8px;
          width: 40%;
          background-color: #DBD5FF;
          color: #7134A6;
        }
        
        .next-btn {
          border-radius: 8px;
          width: 40%;
          background-color: #7134A6;
          color: #F8F5FF;
        }
      }
    }
    
    /* 新增汇总视图样式 */
    .summary-view {
      padding: 20px;
      
      .summary-title {
        font-size: 36rpx;
        font-weight: bold;
        text-align: center;
        margin-bottom: 20px;
        color: $purple-color;
      }
      
      .photos-grid {
        display: flex;
        flex-direction: column;
        gap: 20px;
        
        .photo-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          
          image {
            width: 500rpx;
            height: 500rpx;
            border-radius: 8px;
            border: 1px solid #eee;
          }
          
          .photo-label {
            margin-top: 10px;
            font-size: 28rpx;
            color: $text-color;
          }
        }
      }
      
      .summary-buttons {
        display: flex;
        justify-content: space-between;
        margin-top: 30px;
        
        .re-take-all-btn {
          width: 45%;
          background-color: #DBD5FF;
          color: #7134A6;
          border-radius: 8px;
        }
        
        .submit-btn {
          width: 45%;
          background-color: $primary-color;
          color: white;
          border-radius: 8px;
        }
      }
    }
  }
    
  .tips-container {
    background-color: $card-bg-color;
    margin: 0 -20px;
    padding: 15px 20px;
    border-radius: 0;
    
    .tips-title {
      font-size: 30rpx;
      font-weight: bold;
      margin-bottom: 5px;
    }
    
    .tips-list {
      line-height: 1.5;
      
      .tip-item {
        font-size: 24rpx;
        color: $text-color;
        position: relative;
        padding-left: 25rpx;
        padding-top: 20rpx;
        &::before {
          content: '';
          position: absolute;
          left: 0;
          color: $primary-color;
          font-size: 28rpx;
        }
      }
      
      .tip-bottom {
        font-size: 22rpx;
        color: $text-color;
        position: relative;
        padding-left: 25rpx;
        padding-top: 10rpx;
        
        &::before {
          content: '•';
          position: absolute;
          left: 0;
          color: $primary-color;
          font-size: 28rpx;
        }
      }
    }
  }
}
</style>